package com.lll.simple.rpc.protocol.serialization;

import com.caucho.hessian.io.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author: liull
 * @Description: hessian 序列化
 * @Date: Created in 11:54 2021/2/4
 * @Modified By:
 */
public class HessianSerialization implements RpcSerialization {
    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        if (null == obj) {
            throw new NullPointerException();
        }
        byte[] res;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            Hessian2Output output = new HessianSerializerOutput(os);
            output.writeObject(obj);
            output.flush();
            res = os.toByteArray();
        } catch (Exception e) {
            throw new SerializationException(e);
        }
        return res;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        if (data.length == 0) {
            return null;
        }
        T result;
        try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
            Hessian2Input input = new HessianSerializerInput(is);
            result = (T) input.readObject(clazz);
        } catch (Exception e) {
            throw new SerializationException(e);
        }
        return result;
    }
}
